﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WAD.Model;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;

namespace WAD.DAL
{
    /// <summary>
    /// 分享的数据库操作类
    /// </summary>
    public class DaoShared : DAO
    {
        /// <summary>
        /// 添加一条分享
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static int Add(MShared m)
        {
            String sql = "insert into shared([user_id],advert_id,article_id,url,url_title,url_logo,[type],advert_ids)values(@user_id,@advert_id,@article_id,@url,@url_title,@url_logo,@type,@advert_ids);select @@IDENTITY";
            Database db = GetDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@user_id", DbType.Int32, m.user_id);
            db.AddInParameter(cmd, "@advert_id", DbType.Int32, m.advert_id);
            db.AddInParameter(cmd, "@article_id", DbType.Int32, m.article_id);
            db.AddInParameter(cmd, "@url", DbType.String, m.url);
            db.AddInParameter(cmd, "@url_title", DbType.String, m.url_title);
            db.AddInParameter(cmd, "@url_logo", DbType.String, m.url_logo);
            db.AddInParameter(cmd, "@type", DbType.String, m.type);
            db.AddInParameter(cmd, "@advert_ids", DbType.String, m.advert_ids);
            object o = db.ExecuteScalar(cmd);
            return Convert.ToInt32(o);
        }

        /// <summary>
        /// 用户以分享数+1
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static bool UpdateSharedNum(MShared m)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("update shared set shared_num = shared_num + 1 where id = (select max(id) from shared where [user_id] =  ").Append(m.user_id).Append(" and [type] = ").Append(m.type).Append(" and advert_id = ").Append(m.advert_id);

            if (m.type == 1)
            {
                sb.Append(" and article_id = ").Append(m.article_id);
            }
            else
            {
                sb.Append(" and url = '").Append(m.url).Append("'"); ;
            }
            sb.Append(")");

            return ExecuteNonQuery(sb.ToString()) > 0;
        }

        /// <summary>
        /// 通过分享信息获取id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static int GetIdByInfo(MShared m)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("select top 1 id from shared where advert_id={0} and [type]={1}", m.advert_id, m.type);

            if (m.id > 0)
                sb.AppendFormat(" and [id]={0}", m.id);
            else if (m.user_id > 0)
                sb.AppendFormat(" and user_id={0}", m.user_id); //若地址没带ID参数，则按用户ID统计(刚生成新的分享链接时，没有带ID参数)

            if (m.article_id > 0)
                sb.AppendFormat(" and article_id ={0}", m.article_id);

            if (!string.IsNullOrEmpty(m.url))
                sb.AppendFormat(" and url ='{0}'", m.url);

            //if (m.type == 1)
            //{
            //    sb.AppendFormat(" and article_id ={0}", m.article_id);
            //}
            //else
            //{
            //    sb.AppendFormat(" and url ='{0}'", m.url);
            //}

            //最新的一条记录
            //sql += " order by [date] desc";

            Database db = GetDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sb.ToString());

            object val = db.ExecuteScalar(cmd);
            if (val == null) return 0;
            return (int)val;
        }


        /// <summary>
        /// 根据文章ID，广告ID条件判断是否存在(添加广告链接时用)
        /// </summary>
        /// <param name="type">1 站内文章,2 网络URL</param>
        /// <param name="userId"></param>
        /// <param name="ad_id"></param>
        /// <param name="articleId"></param>
        /// <param name="url">网络URL地址</param>
        /// <returns></returns>
        public static int SharedCount(int group, int userId, int advertId, int articleId, string url)
        {
            //免费客户
            if (group == 0)
            {
                Dictionary<string, object> model = DAO.BindMap("select top 1 advert_id,article_id,url from shared where user_id=" + userId);
                if (model == null)
                    return 0;
                if (articleId > 0 && articleId == Convert.ToInt32(model["article_id"]))
                {
                    if (advertId > 0 && advertId == Convert.ToInt32(model["advert_id"]))
                        return 1;
                }

                if (url != "" && url.Equals(Convert.ToString(model["url"])))
                {
                    return 1;
                }
                return 2;
            }

            //正式客户
            if (group == 1)
            {
                string sql = "";
                if (articleId > 0)
                    sql = string.Format("select count(id) from shared where state=1 and user_id={0} and advert_id={1} and article_id={2}", userId, advertId, articleId);
                else if (!string.IsNullOrEmpty(url))
                    sql = string.Format("select count(id) from shared where state=1 and user_id={0} and advert_id={1} and url='{2}'", userId, advertId, url);

                Database db = GetDatabase();
                DbCommand cmd = db.GetSqlStringCommand(sql);
                int count = Convert.ToInt32(db.ExecuteScalar(cmd));
                if (count == 0) return 0;
                if (count > 0) return 1;   //0 没找到,1已添加，2不允许在次添加
            }

            return 2;
        }


        public static int IsAdd(int group, int userId, int advertId, int articleId, string url, String advert_ids)
        {
            //免费客户
            if (group == 0)
            {
                Dictionary<string, object> model = DAO.BindMap("select top 1 [id],advert_id,article_id,url from shared where user_id=" + userId);
                if (model != null)
                {
                    if (articleId > 0 && articleId == Convert.ToInt32(model["article_id"]))
                    {
                        if (advertId > 0 && advertId == Convert.ToInt32(model["advert_id"]))
                            return Convert.ToInt32(model["id"]);
                    }

                    if (url != "" && url.Equals(Convert.ToString(model["url"])))
                    {
                        return Convert.ToInt32(model["id"]);
                    }

                    return -500;   //系统异常
                }
                return 0;               //不存在
            }

            //正式客户
            if (group == 1)
            {
                string sql = "";
                if (articleId > 0)
                    sql = string.Format("select top 1 [id] from shared where state=1 and user_id={0} and advert_id={1} and article_id={2} and advert_ids = '{3}'", userId, advertId, articleId, advert_ids);
                else if (!string.IsNullOrEmpty(url))
                    sql = string.Format("select top 1 [id] from shared where state=1 and user_id={0} and advert_id={1} and url='{2}' and advert_ids = '{3}'", userId, advertId, url, advert_ids);

                Database db = GetDatabase();
                DbCommand cmd = db.GetSqlStringCommand(sql);
                object o = db.ExecuteScalar(cmd);
                if (o == null || o.ToString().Equals(""))
                    return 0;
                return Convert.ToInt32(o);
            }

            return 0;
        }

        public static int IsAdd2(int group, int userId, int advertId, int articleId, string url, String advert_ids)
        {
           
                string sql = "";
                if (articleId > 0)
                    sql = string.Format("select top 1 [id] from shared where state=1 and user_id={0} and advert_id={1} and article_id={2} and advert_ids = '{3}'", userId, advertId, articleId, advert_ids);
                else if (!string.IsNullOrEmpty(url))
                    sql = string.Format("select top 1 [id] from shared where state=1 and user_id={0} and advert_id={1} and url='{2}' and advert_ids = '{3}'", userId, advertId, url, advert_ids);

                Database db = GetDatabase();
                DbCommand cmd = db.GetSqlStringCommand(sql);
                object o = db.ExecuteScalar(cmd);
                if (o == null || o.ToString().Equals(""))
                    return 0;
                return Convert.ToInt32(o);
        }

        ///// <summary>
        ///// 获取一个实体对象到map对象
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public static Dictionary<string, object> GetEntityMap(int id)
        //{
        //    String sql = "select id,article_id,[type],url,[date],article_content,CONVERT(varchar(20), article_date, 20) article_date,article_logo,article_title,advert_id,article_click from v_shared where [state] = 1 and article_state = 1 and id = " + id;
        //    return BindMap(sql);
        //}

        /// <summary>
        /// 删除一条分享
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public static bool Delete(int id, int userId)
        {
            String sql = "delete shared where id = " + id + " and user_id = " + userId;
            return ExecuteNonQuery(sql) > 0;
        }

        /// <summary>
        /// 隐藏该条分享
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public static bool Hide(int id, int userId)
        {
            String sql = "update shared set [state] = 0 where id = " + id + " and user_id = " + userId;
            return ExecuteNonQuery(sql) > 0;
        }

        /// <summary>
        /// 修改广告
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static bool UpdateAd(MShared m)
        {
            String sql = "update shared set advert_id = @advert_id where [user_id] = @user_id and id = @id";
            Database db = GetDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@advert_id", DbType.Int32, m.advert_id);
            db.AddInParameter(cmd, "@user_id", DbType.Int32, m.user_id);
            db.AddInParameter(cmd, "@id", DbType.Int32, m.id);
            return db.ExecuteNonQuery(cmd) > 0;
        }


        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页显示的总条数</param>
        /// <returns></returns>
        public static PageData GetList(int pageIndex, int pageSize, int userId, bool isOther)
        {
            String fieldList = "id,CONVERT(varchar(20), [date], 20) [date],url_title,url_logo,article_logo,article_title,click,ad_click,type,article_id,advert_id,url";
            String orderBy = "id desc";
            String where = "[user_id] = " + userId + " and [state] = 1";
            String tableName = "v_shared";

            if (isOther)
            {
                where += " and isnull(author_id,0) != " + userId;
            }

            return GetPageList(fieldList, orderBy, pageIndex, pageSize, where, tableName);
        }

        /// <summary>
        /// 根据一篇文章的id 去获取作者的分享信息
        /// </summary>
        /// <param name="articleId"></param>
        public static MShared GetAuthorShared(int articleId, int user_id)
        {
            string sql;
            if (user_id > 0)
                sql = "select top 1 [id],[user_id],advert_id,article_id,type from shared where article_id = " + articleId + " and user_id=" + user_id + " and [state] = 1 order by id ";
            else
                sql = "select top 1 [id],[user_id],advert_id,article_id,type from shared where [user_id] = (select [user_id]  from article where id = " + articleId + ") and article_id = " + articleId + " and [state] = 1 order by id desc";

            object obj = BindEntity(sql, new MShared());
            return obj == null ? null : (MShared)obj;
        }


        /// <summary>
        /// 获取文章浏览需要的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static MShared GetInfo(int id)
        {
            String sql = "select id,[user_id],advert_id,article_id,url,url_logo,url_title,type,advert_ids,state from shared where id = " + id + " and [state] is not null";
            object obj = BindEntity(sql, new MShared());
            return obj == null ? null : (MShared)obj;
        }

        public static MShared GetInfoByUserId(int userid)
        {
            String sql = "select top 1 id,[user_id],advert_id,article_id,url,type from shared where user_id = " + userid;
            object obj = BindEntity(sql, new MShared());
            return obj == null ? null : (MShared)obj;
        }

        /// <summary>
        /// 获取外部链接logo
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static String GetUrlLogo(String url)
        {
            String sql = "select top 1 url_logo from shared where url = '" + url + "'";
            return ExecuteScalar(sql).ToString();
        }

        /// <summary>
        /// 文章是否存在
        /// </summary>
        /// <param name="ad_id"></param>
        /// <param name="userid"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        public static bool IsExists(int ad_id, int articleid, int sharedid, string url, int parentid = 0)
        {
            if (articleid > 0)
            {
                string sql = string.Format("select count(id) from shared where [state]={0} and article_id ={1} and advert_id={2}", 1, articleid, ad_id);
                if (parentid > 0)
                    sql = string.Format("select count(id) from shared where ([state]={0} and article_id ={1} and advert_id={2}) or ([state]={0} and article_id={1} and advert_id={2}) ", 1, articleid, ad_id);

                Database db = GetDatabase();
                DbCommand cmd = db.GetSqlStringCommand(sql);
                if (Convert.ToInt32(db.ExecuteScalar(cmd)) > 0)
                    return true;
            }
            else if (sharedid > 0)
            {
                Database db = GetDatabase();
                DbCommand cmd = db.GetSqlStringCommand(string.Format("select count(id) from shared where  [id] ='{0}'", sharedid));
                if (Convert.ToInt32(db.ExecuteScalar(cmd)) > 0)
                    return true;
            }
            else if (!string.IsNullOrEmpty(url))
            {
                Database db = GetDatabase();
                DbCommand cmd = db.GetSqlStringCommand(string.Format("select count(id) from shared where [state]={0} and advert_id={1} and url ='{2}'", 1, ad_id, url));
                if (Convert.ToInt32(db.ExecuteScalar(cmd)) > 0)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="top"></param>
        /// <param name="where"></param>
        /// <param name="orderby"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public static List<Dictionary<string, object>> GetListTop(int top, string where, string orderby = "", string fields = "*")
        {
            if (string.IsNullOrEmpty(orderby))
                return GetList(string.Format("select top {0} {1} from shared where {2}", top, fields, where));
            else
                return GetList(string.Format("select top {0} {1} from shared where {2} order by {3}", top, fields, where, orderby));
        }
    }
}
